#ifndef TESTWIDGET_H
#define TESTWIDGET_H

#include <QObject>
#include <QWidget>
#include <mymap.h>

class CustomScene;

class NodeItem;

class CustomGraphicsView : public QGraphicsView {
    Q_OBJECT
public:
    explicit CustomGraphicsView(QWidget* parent = nullptr);

protected:
    void wheelEvent(QWheelEvent* event) override;
    void mousePressEvent(QMouseEvent* event) override;

private:
    QPointF m_lastMousePos;
};

class testWidget : public QWidget
{
    Q_OBJECT
public:
    explicit testWidget(QWidget *parent = nullptr);
    ~testWidget();

private slots:
    void handleNodeClicked(NodeItem* node, QPointF pos);
    void handleNodesConnected(NodeItem* start, NodeItem* end);

private:
    CustomScene *scene;
    CustomGraphicsView *view;
    myMap* m_map;
    int nodeNum = 0;

signals:
};

class LineItem;

class NodeItem : public QGraphicsItem
{
public:
    NodeItem(const QString &name, const QPointF &pos, const int ID);

    QRectF boundingRect() const override;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
    // 新增连接管理
    void addConnection(LineItem* connection);
    QList<LineItem*> connections() const { return m_connections; }
    QList<NodeItem*> connectedNodes() const;
    QPointF& getPos();
    int getID() const;

private:
    QString m_name;
    QList<LineItem*> m_connections;
    QPointF m_pos;
    const int m_ID;
};

// 自定义场景
class CustomScene : public QGraphicsScene
{
    Q_OBJECT
public:
    explicit CustomScene(QObject* parent = nullptr);
protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event) override;

signals:
    void nodeClicked(NodeItem* node, QPointF pos);
    void nodesConnected(NodeItem* start, NodeItem* end);
private:
    // 新增成员变量用于记录首次点击的节点
    NodeItem* m_selectedNode = nullptr;
};

class LineItem : public QGraphicsLineItem {
public:
    LineItem(NodeItem* startNode, NodeItem* endNode, QGraphicsItem* parent = nullptr);

    void updatePosition();
    NodeItem* startNode() const { return m_startNode; }
    NodeItem* endNode() const { return m_endNode; }

private:
    NodeItem* m_startNode;
    NodeItem* m_endNode;
};

#endif // TESTWIDGET_H
